package com.wumeng.dynamicmultidatabase01.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wumeng 2022/8/11 3:13 下午
 */
@Data
@Configuration
@ConfigurationProperties("common")
public class PersistenceConfiguration {
    private List<DataSourceModel> jdbc;

    @Primary
    @Bean(name = "multiRoutingDataSource")
    public DataSource multiRoutingDataSource() {
        Map<Object, Object> targetDataSources = new HashMap<>();

        HikariDataSource mainDataSource = null;
        if (jdbc!=null&&jdbc.size()>0){
            for (int i = 0; i < jdbc.size() ; i++) {
                HikariDataSource dataSource= new HikariDataSource();
                dataSource.setDriverClassName(jdbc.get(i).getDriverClassName());
                dataSource.setPassword(jdbc.get(i).getPassword());
                dataSource.setUsername(jdbc.get(i).getUserName());
                dataSource.setJdbcUrl(jdbc.get(i).getUrl());
//                dataSource.setMaximumPoolSize(6000);
                targetDataSources.put(jdbc.get(i).getKey(),dataSource);
                if (i == 0){
                    // 将该数据源设置成默认数据源
                    mainDataSource = dataSource;
                }
            }
        }

        MultiRoutingDataSource multiRoutingDataSource = new MultiRoutingDataSource();
        if (mainDataSource!=null){
            multiRoutingDataSource.setDefaultTargetDataSource(mainDataSource);
        }
        multiRoutingDataSource.setTargetDataSources(targetDataSources);
        return multiRoutingDataSource;
    }


}
